﻿using Application.Commons.Data;
using AutoMapper;
using Domain.Entities.Customers;
using Domain.Events;
using FrameworkCore.Attributes;
using FrameworkCore.Helpers;
using FrameworkCore.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;

namespace NM.Module.Cust.API.Commands.Create;

/// <summary>
/// 创建用户
/// </summary>
[Map(typeof(Customer))]
public class CreateCustomerCommand : IRequest<Result<long>>
{
    /// <summary>
    /// 用户名
    /// </summary>
    [Required(ErrorMessage = "用户名必传")]
    public required string Username { get; set; }

    /// <summary>
    /// 密码
    /// </summary>
    [Required(ErrorMessage = "密码必传")]
    public required string Password { get; set; }

    /// <summary>
    /// 电子邮箱
    /// </summary>
    public string? Email { get; set; }
}

public class CreateCustomerCommandHandler : IRequestHandler<CreateCustomerCommand, Result<long>>
{
    private readonly ApplicationDbContext _context;
    private readonly IMapper _mapper;

    public CreateCustomerCommandHandler(
        ApplicationDbContext context, 
        IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    public async Task<Result<long>> Handle(CreateCustomerCommand request, CancellationToken cancellationToken)
    {
        var existUsername = await _context.Customers
            .AnyAsync(x => x.Username == request.Username, cancellationToken);
        ExceptionHelper.ThrowIfTrue(existUsername, "用户名已存在");

        var existEmail = await _context.Customers
            .AnyAsync(x => x.Email == request.Email, cancellationToken);
        ExceptionHelper.ThrowIfTrue(existEmail, "邮箱已存在");

        var item = _mapper.Map<Customer>(request);
        item.AddDomainEvent(new CreatedEvent<Customer>(item));
        _context.Customers.Add(item);
        await _context.SaveChangesAsync(cancellationToken);

        return await Result<long>.SucceedAsync(item.Id);
    }
}